<?php
require_once "db.class.php";
require_once "config.inc.php";

$DB = new db();
if ($DB)
    $DB->connect(TT_DBHOST, TT_DBUSER, TT_DBPW, TT_DBNAME, TT_DBCHARSET);
else
    exit("cann't init database");

function fs_location($pid, $ext){
    $dir = substr($pid, 0, 2);
    return "/upload/$dir/$pid.$ext";
}

function pic_insert($pid, $ext){
    global $DB;
    $url = fs_location($pid, $ext);
    $query = "INSERT INTO ".TT_DBTABLEPRE. "pic(`id`, `url`) VALUES ('$pid', '$url');";
    $DB->query($query);
    return $pid;
}
function pic_get_by_sql($query){
    global $DB;
    $rst = $DB -> fetch_first($query);
    $marks = json_decode (base64_decode($rst['marks']));
    $o = array(
        'id' => $rst['id'],
        'url' => $rst['url'],
        'marks' => $marks,
        'modify_time' => $rst['modify_time'],
        );
    return $o;
}

function next_pic_info($pid){
    $query = "SELECT * FROM ss_pic WHERE modify_time > (select modify_time from ss_pic where id='$pid') order by modify_time limit 1;";
    return pic_get_by_sql($query);
}

function last_pic_info($pid){
    $query = "SELECT * FROM ss_pic WHERE modify_time < (select modify_time from ss_pic where id='$pid') order by modify_time desc limit 1;";
    return pic_get_by_sql($query);
}

function pic_info($pid){
    $query = "SELECT * FROM ss_pic WHERE id = '$pid';";
    $p = pic_get_by_sql($query);
    $last = last_pic_info($pid);
    $next = next_pic_info($pid);
    $p['prev'] = $last;
    $p['next'] = $next; //TODO:too many querys
    return $p;

}

